package org.example.Maskter;

import java.nio.channels.Pipe;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

//分配任务，聚合任务结果
//workers 中的线程，要去从workQueue中取任务，然后再将结果放到resultMap
public class Master {
    //1.有一个承装任务的容器
    private ConcurrentLinkedQueue<Task> workQueue = new ConcurrentLinkedQueue<>();

    //2.承装所有的worker对象
    private HashMap<String,Thread> workers = new HashMap<>();

    //3.承装有一个worker并发处理的任务结果集
    private ConcurrentHashMap<String, Object> resultMap = new ConcurrentHashMap<>();

    //4.构造任务，创建多个worker对象
    public Master(Worker worker,int workerCount){
        //每一个worker对象都需要master的引用
        worker.setResultMap(this.resultMap);
        worker.setWorkQueue(this.workQueue);

        for (int i= 0;i<workerCount;i++){
            this.workers.put(Integer.toString(i),new Thread(worker));
        }

    }

    //5.需要一个提交任务的方法

    public void submitTask(Task task){
        this.workQueue.add(task);
    }

    //6.启动所有worker对象执行任务
    public void execute(){
        for (Map.Entry<String,Thread> me : workers.entrySet()){
            me.getValue().start();
        }
    }

    //7.判断所有的worker是否运行结束
    public boolean isStop(){
        for (Map.Entry<String,Thread> me : workers.entrySet()){
            if (me.getValue().getState() != Thread.State.TERMINATED)
                return false;
        }
        return true;
    }

    //计算结果
    public int getResult(){
        int priceResult = 0;
        for (Map.Entry<String,Object> me : resultMap.entrySet()){
            priceResult += (int)me.getValue();
        }
        return priceResult;
    }



}
